package cn.lblbc.downloadlib;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 文件下载器
 */
public class FileDownloader {
    private static final String TAG = "FileDownloader";
    private final OkHttpClient mHttpClient;
    private final ExecutorService mExecutorService;

    public FileDownloader() {
        mHttpClient = new OkHttpClient();
        mExecutorService = Executors.newFixedThreadPool(3);
    }

    /**
     * 下载单个文件
     * @param fileInfo 文件信息
     * @param callback 下载回调
     */
    public void downloadFile(DownloadFileInfo fileInfo, DownloadCallback callback) {
        Log.d(TAG, "downloadFile: Starting download for file: " + fileInfo.getFileName());
        mExecutorService.execute(() -> {
            try {
                // 确保目标目录存在
                File targetFile = new File(fileInfo.getLocalPath());
                File parentDir = targetFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                // 创建请求
                Request request = new Request.Builder()
                        .url(fileInfo.getFileUrl())
                        .build();

                // 执行请求
                Response response = mHttpClient.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                // 写入文件
                try (InputStream inputStream = response.body().byteStream();
                     FileOutputStream outputStream = new FileOutputStream(targetFile)) {
                    
                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    long totalBytesRead = 0;
                    long contentLength = response.body().contentLength();
                    
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        
                        // 回调进度
                        if (contentLength > 0) {
                            int progress = (int) ((totalBytesRead * 100) / contentLength);
                            callback.onProgress(progress, totalBytesRead, contentLength);
                        }
                    }
                    
                    Log.d(TAG, "downloadFile: File downloaded successfully: " + fileInfo.getFileName());
                    callback.onSuccess(fileInfo);
                }
            } catch (Exception e) {
                Log.e(TAG, "downloadFile: Error downloading file: " + fileInfo.getFileName(), e);
                callback.onError(fileInfo, e);
            }
        });
    }

    /**
     * 下载单个文件（支持暂停）
     * @param fileInfo 文件信息
     * @param callback 下载回调
     * @param pauseChecker 暂停检查器
     */
    public void downloadFile(DownloadFileInfo fileInfo, DownloadCallback callback, PauseChecker pauseChecker) {
        Log.d(TAG, "downloadFile: Starting download for file: " + fileInfo.getFileName());
        mExecutorService.execute(() -> {
            try {
                // 确保目标目录存在
                File targetFile = new File(fileInfo.getLocalPath());
                File parentDir = targetFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                // 创建请求
                Request request = new Request.Builder()
                        .url(fileInfo.getFileUrl())
                        .build();

                // 执行请求
                Response response = mHttpClient.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                // 写入文件
                try (InputStream inputStream = response.body().byteStream();
                     FileOutputStream outputStream = new FileOutputStream(targetFile)) {
                    
                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    long totalBytesRead = 0;
                    long contentLength = response.body().contentLength();
                    
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        // 检查是否需要暂停
                        if (pauseChecker != null && pauseChecker.isPaused()) {
                            Log.d(TAG, "downloadFile: Download paused for file: " + fileInfo.getFileName());
                            // 等待直到恢复
                            while (pauseChecker != null && pauseChecker.isPaused()) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    Log.d(TAG, "downloadFile: Thread interrupted while paused");
                                    Thread.currentThread().interrupt();
                                    throw new IOException("Download interrupted", e);
                                }
                            }
                            Log.d(TAG, "downloadFile: Download resumed for file: " + fileInfo.getFileName());
                        }
                        
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        
                        // 回调进度
                        if (contentLength > 0) {
                            int progress = (int) ((totalBytesRead * 100) / contentLength);
                            callback.onProgress(progress, totalBytesRead, contentLength);
                        }
                    }
                    
                    Log.d(TAG, "downloadFile: File downloaded successfully: " + fileInfo.getFileName());
                    callback.onSuccess(fileInfo);
                }
            } catch (Exception e) {
                Log.e(TAG, "downloadFile: Error downloading file: " + fileInfo.getFileName(), e);
                callback.onError(fileInfo, e);
            }
        });
    }

    /**
     * 下载回调接口
     */
    public interface DownloadCallback {
        /**
         * 下载进度回调
         * @param progress 进度百分比
         * @param downloadedBytes 已下载字节数
         * @param totalBytes 总字节数
         */
        void onProgress(int progress, long downloadedBytes, long totalBytes);
        
        /**
         * 下载成功回调
         * @param fileInfo 文件信息
         */
        void onSuccess(DownloadFileInfo fileInfo);
        
        /**
         * 下载失败回调
         * @param fileInfo 文件信息
         * @param error 错误信息
         */
        void onError(DownloadFileInfo fileInfo, Exception error);
    }
    
    /**
     * 暂停检查器接口
     */
    public interface PauseChecker {
        boolean isPaused();
    }
}